#include <stdio.h>
#include <string.h>

struct student
{
    char *name;
    int age;
};
// 多个字节的内容，按字节交换顺序。
void swap(char *buf1, char *buf2, int width)
{
    for (int i = 0; i < width; i++)
    {
        char temp = *buf1;
        *buf1 = *buf2;
        *buf2 = temp;
        buf1++;
        buf2++;
    }
}
// 按地址解引用 比较两个int数据值的大小
int cmp_int(const void *p1, const void *p2)
{
    return *(int *)p1 - *(int *)p2;
}
// 按年龄排序
int cmp_by_age(const void *p1, const void *p2)
{
    return (*(struct student *)p1).age - (*(struct student *)p2).age;
}
// 按字母顺序排序
// int strcmp(const char *s1,const char *s2);
int cmp_by_name(const void *p1, const void *p2)
{
    return strcmp((*(struct student *)p1).name, (*(struct student *)p2).name);
}
void bubbleSort(void *base, int sz, int width, int (*cmp)(const void *e1, const void *e2)){
    for (int i = 0; i < sz; i++) {
        for(int j=0;j<sz-1-i;j++){
            if(cmp((char*)base + width * j, (char*)base + width * (j+1)) > 0){
                swap((char*)base + width * j, (char*)base + width * (j+1), width);
            }
        }
    }
}

// 冒泡排序
int main()
{
    int arr[] = {9,8,7,6,5,4,3,2,1,0};
    int sz = sizeof(arr)/sizeof(arr[0]);
    bubbleSort(arr, sz, sizeof(arr[0]), &cmp_int);
    for(int i=0;i<sz;i++){
        printf("%d ",arr[i]);
    }
    printf("\n");

    struct student stu_arr[] = {{"zhangsan", 20}, {"lisi", 30}, {"wangwu", 10}};
    int szEx = sizeof(stu_arr) / sizeof(stu_arr[0]);
    bubbleSort(stu_arr, szEx, sizeof(stu_arr[0]), &cmp_by_age);
    for (int i = 0; i < szEx; i++)
    {
        printf("%s %d \n", stu_arr[i].name, stu_arr[i].age);
    }
    printf("\n");

    bubbleSort(stu_arr, szEx, sizeof(stu_arr[0]), &cmp_by_name);
    for (int i = 0; i < szEx; i++)
    {
        printf("%s %d \n", stu_arr[i].name, stu_arr[i].age);
    }
    return 0;
}
